//
//  YPZQApplyViewController.m
//  ChengHuiTong
//
//  Created by CHT-Technology on 2017/2/22.
//  Copyright © 2017年 张文权. All rights reserved.
//

#import "YPZQApplyViewController.h"
#import "MoneyTextField.h"
@interface YPZQApplyViewController (){
    
    TPKeyboardAvoidingScrollView *_bgScrollView;
    MoneyTextField *_zrMoneyTF;
    UILabel *_sxfLabel;
    UILabel *_returnMoneyLabel;
    UITextField *_zdCodeTF;
    
    NSDictionary *_dataDic; //数据字典
    NSString *_kcString; //需要扣除金额
    NSString *_smsid; //短信ID
    
}

@end

@implementation YPZQApplyViewController
#define rowHight autoScaleH(44)
#define additionalHeight autoScaleH(18)
#define sepeHeight autoScaleH(12)
- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.navigationItem.title = @"申请债权转让";
    
    [self setUpData];
    
}

#pragma mark -- Private Methods
- (void)setUpData{
    
    [YPHttpRequestMethod sendAsyRequestURL:CMD_ZQAPPLY withData:@{@"token":TOKEN,@"tender_id":REALSTRING(_tender_id)} withCompletionBlock:^(NSDictionary *responseDictionary) {
        
        if ([responseDictionary[@"status"] integerValue] == 0) {
            
            _dataDic = responseDictionary;
            [self setUpUI];
        }
        
    } withFailedBlock:^(NSError *error) {

        
    }withIndicator:YES  atView:self.view];
}

- (void)setUpUI{
    
    _bgScrollView = [[TPKeyboardAvoidingScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
    _bgScrollView.backgroundColor = self.view.backgroundColor;
    _bgScrollView.contentSize = CGSizeMake(SCREEN_WIDTH, _bgScrollView.height + 1);
    [self.view addSubview:_bgScrollView];

    [self AddSectionsContent];
    
}

- (void)AddSectionsContent{
    
    NSArray *heightArray = @[@(rowHight*3+additionalHeight*2),@(rowHight*2+additionalHeight*3),@(rowHight),@(rowHight*2)];
    CGFloat top = sepeHeight;
    for (int i = 0; i < heightArray.count; i ++) {
        
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, top , SCREEN_WIDTH, [heightArray[i] floatValue])];
        view.backgroundColor = [UIColor whiteColor];
        [_bgScrollView addSubview:view];
        top += ([heightArray[i] floatValue] + sepeHeight);
        
    }

    
    //项目名称
    UILabel *titleLabel = [self creatLabelWithTop:sepeHeight
                                   attributedText:[self getAttributedStringWithChangeTextColor:[UIColor blackColor]
                                                                                originalString:[NSString stringWithFormat:@"项目转让 : %@",_dataDic[@"title"]]
                                                                                  changeString:_dataDic[@"title"]]];
    [titleLabel addLine];
    [_bgScrollView addSubview:titleLabel];
    
    
    //剩余价值
    UILabel *syValue = [self creatLabelWithTop:titleLabel.bottom
                                attributedText:[self getAttributedStringWithChangeTextColor:[UIColor blackColor]
                                                                             originalString:[NSString stringWithFormat:@"债权剩余价值 : %@ 元",_dataDic[@"credit_value"]]
                                                                               changeString:_dataDic[@"credit_value"]]];
    [_bgScrollView addSubview:syValue];
    [self additionalViewWithText:[NSString stringWithFormat:@"待还本金%@元，利息%@元",_dataDic[@"wait_capital"],_dataDic[@"wait_interest"]]
                             top:syValue.bottom];
    
    
    //转让金额
    _zrMoneyTF = [[MoneyTextField alloc]initWithFrame:CGRectMake(leftMargin, syValue.bottom + additionalHeight, SCREEN_WIDTH - leftMargin*2, rowHight)];
    [_zrMoneyTF addTarget:self action:@selector(inputChange) forControlEvents:UIControlEventEditingChanged];
    [self configTextField:_zrMoneyTF placehold:@"请输入转让金额" leftViewTitle:@"转让金额 : "];
    [_bgScrollView addSubview:_zrMoneyTF];
    [self additionalViewWithText:[NSString stringWithFormat:@"最大可转金额:%@元",_dataDic[@"wait_capital"]] top:_zrMoneyTF.bottom];
    
    
    //需要扣除金额
    _kcString = [NSString stringWithFormat:@"%.2f",[_dataDic[@"award_tender"] doubleValue]+[_dataDic[@"award_tenderagain"] doubleValue]+[_dataDic[@"award_interest"] doubleValue] + [_dataDic[@"award_point_value"] doubleValue]];
    UILabel *kcMoney = [self creatLabelWithTop:_zrMoneyTF.bottom + sepeHeight + additionalHeight
                                attributedText:[self getAttributedStringWithChangeTextColor:[UIColor blackColor]
                                                                             originalString:[NSString stringWithFormat:@"需要扣除金额 : %@ 元",_kcString]
                                                                               changeString:_kcString]];
    [_bgScrollView addSubview:kcMoney];
    [self additionalViewWithText:[NSString stringWithFormat:@"投资奖励%@元，续投奖励%@元\n加息收益%@元，投资积分%@元",_dataDic[@"award_tender"],_dataDic[@"award_tenderagain"],_dataDic[@"award_interest"],_dataDic[@"award_point_value"]]
                             top:kcMoney.bottom];
    
    
    //转让手续费
    _sxfLabel = [self creatLabelWithTop:kcMoney.bottom + additionalHeight*2
                                attributedText:[self getAttributedStringWithChangeTextColor:[UIColor blackColor]
                                                                             originalString:@"转让手续费 : 0.00 元"
                                                                               changeString:@"0.00" ]];
    [_bgScrollView addSubview:_sxfLabel];
    [self additionalViewWithText:[NSString stringWithFormat:@"债权持有%@期，按转让金额%@%%收取",_dataDic[@"repayyes_count"],_dataDic[@"fee_rate"]] top:_sxfLabel.bottom];
    
    
    //转让后预计回收总额
    _returnMoneyLabel = [self creatLabelWithTop:_sxfLabel.bottom + sepeHeight + additionalHeight
                                    attributedText:[self getAttributedStringWithChangeTextColor:kColor_redNumberColor
                                                                                 originalString:@"转让后预计回收总额=  0.00元"
                                                                                   changeString:@"0.00" ]];
    [_bgScrollView addSubview:_returnMoneyLabel];
    
    
    //手机号码
    NSString *phoneString = [_dataDic[@"phone"] stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    UILabel *phoneNum = [self creatLabelWithTop:_returnMoneyLabel.bottom + sepeHeight
                                 attributedText:[self getAttributedStringWithChangeTextColor:[UIColor blackColor]
                                                                              originalString:[NSString stringWithFormat:@"手机号码 : %@",phoneString]
                                                                                changeString:phoneString]];
    [phoneNum addLine];
    [_bgScrollView addSubview:phoneNum];
    
    
    //验证码
    _zdCodeTF = [[UITextField alloc]initWithFrame:CGRectMake(_zrMoneyTF.left, phoneNum.bottom , _zrMoneyTF.width, _zrMoneyTF.height)];
    _zdCodeTF.keyboardType = UIKeyboardTypeNumberPad;
    [self configTextField:_zdCodeTF placehold:@"请输入手机验证码" leftViewTitle:@"验证码 : "];
    UIButton *rightBtn = [UIButton creatWithFrame:CGRectMake(0, autoScaleH(8), 80, _zdCodeTF.height - autoScaleH(8)*2)
                                             font:[UIFont systemFontOfSize:13]
                                             text:@"获取验证码"
                                        textColor:kColor_AppNavColor
                                           action:@selector(getPhoneCode:)
                                           target:self];
    [rightBtn setBorderWithColor:kColor_AppNavColor borderWidth:1];
    rightBtn.layer.cornerRadius = autoScaleW(5);
    rightBtn.layer.masksToBounds = YES;
    _zdCodeTF.rightView = rightBtn;
    _zdCodeTF.rightViewMode = UITextFieldViewModeAlways;
    [_bgScrollView addSubview:_zdCodeTF];
    
    
    //确认转让
    UIButton *sureBtn = [UIButton creatWithFrame:CGRectMake(autoScaleW(40), _zdCodeTF.bottom + sepeHeight*2, (SCREEN_WIDTH - autoScaleW(40)*2 - leftMargin)/2.f, autoScaleH(38))
                                            font:[UIFont systemFontOfSize:17]
                                            text:@"确认转让"
                                          action:@selector(sureAction)
                                          target:self];
    sureBtn.backgroundColor = kColor_AppNavColor;
    [_bgScrollView addSubview:sureBtn];
    
    
    //取消
    UIButton *cancleBtn = [UIButton creatWithFrame:CGRectMake(sureBtn.right + leftMargin, sureBtn.top, sureBtn.width, sureBtn.height)
                                            font:sureBtn.titleLabel.font
                                            text:@"取消"
                                         textColor:[UIColor blackColor]
                                          action:@selector(cancleAction)
                                          target:self];
    [cancleBtn setBorderWithColor:[UIColor lightGrayColor] borderWidth:1];
    [_bgScrollView addSubview:cancleBtn];
    
    
    [_bgScrollView addSubview:[UILabel creatWithFrame:CGRectMake(0, cancleBtn.bottom + sepeHeight, SCREEN_WIDTH, 20)
                                                 font:[UIFont systemFontOfSize:SCREEN_WIDTH < 375?11:13]
                                                 text:@"发起转让后，所有设置均不可更改，请慎重！"
                                            textColor:[UIColor lightGrayColor]
                                        textAlignment:1]];
    
    if (cancleBtn.bottom + sepeHeight > _bgScrollView.height) {
        [_bgScrollView contentSizeToFit];
    }

    
}

- (UILabel *)creatLabelWithTop:(CGFloat)top attributedText:(NSAttributedString *)attString{
    
    UILabel * label = [UILabel creatWithFrame:CGRectMake(leftMargin, top, SCREEN_WIDTH - leftMargin, rowHight)
                               font:[UIFont systemFontOfSize:14]
                               text:@""
                          textColor:kColor_greyAshTitleColor
                      textAlignment:0];
    
    if(attString != nil) label.attributedText = attString;
    return label;
    
}

- (NSAttributedString *)getAttributedStringWithChangeTextColor:(UIColor *)textColor
                                                originalString:(NSString *)originalString
                                                  changeString:(NSString *)changeString
                                                {
    
    NSMutableAttributedString *mAttString = [[NSMutableAttributedString alloc]initWithString:originalString];
    [mAttString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16],
                                NSForegroundColorAttributeName:textColor,
                                } range:[originalString rangeOfString:changeString]];
    if ([originalString rangeOfString:@"元"].location != NSNotFound) {
        [mAttString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:[originalString rangeOfString:@"元"]];
    }
    return mAttString;
}

- (void)additionalViewWithText:(NSString *)text top:(CGFloat)top{
    
    CGFloat height = [text rangeOfString:@"\n"].location == NSNotFound? additionalHeight : additionalHeight*2;
    UIView *additionalView = [[UIView alloc]initWithFrame:CGRectMake(0, top, SCREEN_WIDTH, height)];
    additionalView.backgroundColor = _bgScrollView.backgroundColor;
    [additionalView addLine];
    
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(leftMargin, autoScaleH(3), 2, height - autoScaleH(3)*2)];
    line.backgroundColor = kColor_AppNavColor;
    [additionalView addSubview:line];
    
    UILabel *label = [UILabel creatWithFrame:CGRectMake(line.right + 5, 0, SCREEN_WIDTH - line.right - 10, height)
                                        font:[UIFont systemFontOfSize:SCREEN_WIDTH < 375?10:12]
                                        text:text
                                   textColor:[UIColor lightGrayColor]
                               textAlignment:0];
    label.numberOfLines = 0;
    [additionalView addSubview:label];
    [_bgScrollView addSubview:additionalView];
    
}

- (void)configTextField:(UITextField *)textField
              placehold:(NSString *)placehold
          leftViewTitle:(NSString *)string{
    
    textField.font = [UIFont systemFontOfSize:13];
   
    UILabel *label = [UILabel creatWithFrame:CGRectMake(0, 0, 0, 0)
                                        font:[UIFont systemFontOfSize:14]
                                        text:string
                                   textColor:kColor_greyAshTitleColor
                               textAlignment:0];
    [label sizeToFit];
    label.width += 10;
    textField.leftView = label;
    textField.leftViewMode = UITextFieldViewModeAlways;
    textField.attributedPlaceholder = [[NSAttributedString alloc]initWithString:placehold attributes:@{NSForegroundColorAttributeName:colorWithRGB(225, 225, 225)}];
}


#pragma mark -- 事件响应
- (void)inputChange{
    
    NSString *sxf = [NSString stringWithFormat:@"%.2f",_zrMoneyTF.text.doubleValue*[_dataDic[@"fee_rate"] doubleValue]/100.f];
    _sxfLabel.attributedText = [self getAttributedStringWithChangeTextColor:[UIColor blackColor]
                                                             originalString:[NSString stringWithFormat:@"转让手续费 : %@ 元",sxf]
                                                               changeString:sxf];
    
    NSString *returnString = [NSString stringWithFormat:@"%.2f",_zrMoneyTF.text.doubleValue - sxf.doubleValue - _kcString.doubleValue];
    _returnMoneyLabel.attributedText = [self getAttributedStringWithChangeTextColor:kColor_redNumberColor
                                                                     originalString:[NSString stringWithFormat:@"转让后预计回收总额=  %@元",returnString]
                                                                       changeString:returnString];
}

- (void)getPhoneCode:(UIButton *)btn{
    
    btn.titleLabel.font = [UIFont systemFontOfSize:12];
    btn.enabled = NO;
    
    [YPHttpRequestMethod sendAsyRequestURL:CMD_ZQPHONECODE withData:@{@"token":TOKEN,@"phone":_dataDic[@"phone"]} withCompletionBlock:^(NSDictionary *responseDictionary) {
        
        NSInteger status = [responseDictionary[@"status"] integerValue];
        if (status == 0) {
            
            _smsid = responseDictionary[@"smsid"];
            
            [self openTimerWithLimit:60 progressBlock:^(NSString *seconds){
                
                [btn setTitle:[NSString stringWithFormat:@"重新发送(%@)",seconds] forState:UIControlStateNormal];
                
            } completeBlock:^{
                [btn setTitle:@"获取验证码" forState:UIControlStateNormal];
                [btn setTitleColor:kColor_AppNavColor forState:0];
                btn.titleLabel.font = [UIFont systemFontOfSize:13];
                btn.enabled = YES;
                
            }];
            
        }else{
            
            [MBProgressHUD showError:status == 1304?@"手机号未认证":(status == 1308?@"短信请求过于频繁":@"发送短信失败") toView:self.view];
            btn.enabled = YES;
        }
        
    } withFailedBlock:^(NSError *error) {
        btn.enabled = YES;
    }withIndicator:YES  atView:self.view];
    
    
}

- (void)sureAction{
    
    if (_zrMoneyTF.text.floatValue == 0) {
        
        [MBProgressHUD showError:@"请输入转让金额" toView:self.view];
        return;
    }
    if (_zrMoneyTF.text.doubleValue > [_dataDic[@"wait_capital"] doubleValue]) {
        
        [MBProgressHUD showError:@"转让金额不能超过最大可转金额" toView:self.view];
        return;
    }
    if (REALSTRING(_zdCodeTF.text).length == 0) {
        
        [MBProgressHUD showError:@"请输入手机验证码" toView:self.view];
        return;
    }
//    if (_zrMoneyTF.text.doubleValue < [_dataDic[@"wait_capital"] doubleValue]*0.8) {
//        
//        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"风险提示"
//                                                           message:@"转让金额低于待还本金的80%，是否继续操作?"
//                                                          delegate:self
//                                                 cancelButtonTitle:@"取消"
//                                                 otherButtonTitles:@"继续", nil];
//        [alertView show];
//        return;
//        
//    }
    
    
    [self.view endEditing:YES];
    
    NSString *zrMoney = s_2_Double(_zrMoneyTF.text.doubleValue);
    NSString *jzMoney = _dataDic[@"credit_value"];
    NSString *ssMoney = string(@"本金",  s_2_Double([_dataDic[@"wait_capital"] doubleValue] - _zrMoneyTF.text.doubleValue));
    NSString *content = [NSString stringWithFormat:@"您是否确定一次性以%@元的价格转让%@元(其中待收本金%@元，待收利息%@元)的债权，如果您确定，则将损失%@元，确定请点击确认转让按钮",zrMoney,jzMoney,_dataDic[@"wait_capital"],_dataDic[@"wait_interest"],ssMoney];
    
    NSMutableAttributedString *mAtt = [[NSMutableAttributedString alloc]initWithString:content];
    [mAtt addAttribute:NSForegroundColorAttributeName value:kColor_redNumberColor range:[content rangeOfString:zrMoney]];
    [mAtt addAttribute:NSForegroundColorAttributeName value:kColor_redNumberColor range:[content rangeOfString:jzMoney]];
    [mAtt addAttribute:NSForegroundColorAttributeName value:kColor_redNumberColor range:[content rangeOfString:ssMoney]];
    [mAtt addAttribute:NSForegroundColorAttributeName value:kColor_redNumberColor range:[content rangeOfString:@"一次性"]];
    
    [self showCountDownBoxWithTitle:@"   债权转让确定" contentText:mAtt completeTitle:@"确认转让" cancleTitle:@"再想想" timeLimit:30 completeBlock:^{
        [self commitFormApply];
    }];

    
}

- (void)commitFormApply{
    
    [YPHttpRequestMethod updateRequestURL:CMD_ZQAPPLYPULISH withData:@{@"token":TOKEN,@"tender_id":REALSTRING(_tender_id),@"price":_zrMoneyTF.text,@"smsid":REALSTRING(_smsid),@"code":REALSTRING(_zdCodeTF.text)} withCompletionBlock:^(NSDictionary *responseDictionary) {
        
        NSInteger status = [responseDictionary[@"status"] integerValue];
        if (status == 0) {
            
            if (self.applyCompleteBlock) {
                self.applyCompleteBlock();
            }
            [self.navigationController popViewControllerAnimated:YES];
            
        }else{
            
            [MBProgressHUD showError:status == 1010?@"验证码已失效":(status == 1011?@"验证码不正确":([responseDictionary.allKeys containsObject:@"error"]?responseDictionary[@"error"]:@"提交失败")) toView:self.view];
        }
        
    } withFailedBlock:^(NSError *error) {
        
    } withIndicator:YES atView:self.view];
}

- (void)cancleAction{
    
    [self.navigationController popViewControllerAnimated:YES];
}


@end
